const
	readline = require('readline');

/**
 * class Console
 */
class Console {
	#Version = '0.0.1';
	#Author = 'byhgj';
	title = `Console ${this.#Version}, by ${this.#Author}`;
	handler = {};
	prompt = '> ';
	namespace = {variables:{}};
	customParser = null;
	constructor(opts){
		if (opts.title) this.title = opts.title;
		this.handler = Object.assign(this.handler, opts.handler);
		if (opts.prompt) this.prompt = opts.prompt;
		if (typeof opts.customParser === 'function') this.customParser = opts.customParser;

		this.rl = readline.createInterface({
			input: process.stdin,
			output: process.stdout,
			// 按TAB自动完成
			completer: (line) => {
				const completions = Object.keys(this.handler).sort();
				const hits = completions.filter((c) => c.startsWith(line));
				return [hits.length ? hits : null, line];
			},
			prompt: this.prompt,
			crlfDelay: Infinity
		});

		this.rl.on('line', async (line) => {
			if (line.trim() === '') {
				this.rl.prompt();
				return;
			}
			if (typeof this.customParser === 'function' && (!this.customParser(this, line))){
				this.rl.prompt();
				return;
			}
			line = line.trim().split(' ');
			if (this.handler[line[0]]) {
				await this.handler[line[0]](this, ...line.slice(1))
			} else {
				switch(line[0]){
					case 'exit':
						this.rl.close();
						break;
					default:
						console.log('该命令不支持');
						break;
				}
			}
			this.rl.prompt();
		}).on('SIGINT', () => {
			this.rl.question('exit?(y/N) ', (answer) => {
				if (answer.toLowerCase() === 'y') process.exit();
				else this.rl.prompt();
			})
		}).on('close', () => {
			console.log('BYE.');
			process.exit();
		})
	}
	start(){
		console.log(this.title);
		this.rl.prompt();
	}
}

module.exports = Console;